var app = getApp()

var QQMapWX = require('../../../../utils/qqmap-wx-jssdk.min.js')

const wxMap = new QQMapWX({
  key: 'NSUBZ-2GEKP-AYYDK-LMZXC-KE2LO-46B6H'
})
Page({
    data: {
      params: {
        pageNum: 1,
        pageSize: 9999
      },
      cancelInfo: '',

      pop: false,
      wasActivities:'',

      // 地址列表

      locationList: [],

      bookInfoIds: '',

      shipType: '',

      shippingAddressId: '',
      arr: [],

      hasOrder: false,


      localList: [],

      bookStationId: '',

      shipType: 1,  //邮寄地址 1 自送 2


      showCon: false,//授权弹框

      type: '', //判断配送方式的订单
      orderNo2: '',
      localType: '',

      localNum: 0 //附近收书点数量
    },
    //添加新地址
    addDizhi () {
      wx.navigateTo({
        url: '/package/juanshu/pages/addDizhi/addDizhi',
      })
    },

    //确认支付

    paySuccess () {

      var _this = this
      if (this.data.shippingAddressId == '' || this.data.locationList.length==0) {
        wx.showToast({
          title: '请选择地址',
          icon: 'none'
        })
        return
      }
      var params = {
        bookInfoIds: this.data.bookInfoIds,
        shipType: this.data.shipType,
        shippingAddressId: this.data.shippingAddressId,
        openId: wx.getStorageSync('openid')
      }

      if (this.data.wasActivities!='') {
        params.wasActivities = this.data.wasActivities
      }

      if (this.data.hasOrder) {
        params.orderNo = this.data.options.orderNo
      }


  if (this.data.type == '') {
      this.crateOrder(params)

      return
  }

  if (this.data.type == 1) {
    if (this.data.bookInfoIds.split(',').length < 6) {
      this.wxPay2(this.data.orderNo2)
      return
    }else{
      wx.showToast({
        title: '不要重复下单',
        icon: 'none'
      })
      return
    }
  }

  if (this.data.type == 2) {

    wx.showModal({
      title: '更换配送方式',
      content: '是否更换配送方式',
      success: function (res) {
        if (res.confirm) {
          _this.closePop2(_this.data.orderNo2, params)
        }else{
          return false
        }
      }
    })
    return
  }

      // wx.navigateTo({
      //   url: '/package/juanshu/pages/paySuccess/paySuccess',
      // })
    },




  getStatusopen() {

    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/message/findWasNotice/auth',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {

          if (res.data.data == 0) {
            _this.getMasse()
          }else{
            setTimeout(function(){
              wx.navigateBack()
            },2000)
          }
          // _this.setData({
          //   openNew: res.data.data == 0 ? true : false
          // })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  getDingyue(wasNotice) {

    var _this = this

    var params = {
      wasNotice: wasNotice
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/message/updateWasNotice/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.showToast({
            title: wasNotice == 0 ? '取消授权' : '授权成功',
            icon: 'none'
          })
          setTimeout(function(){
            wx.navigateBack()
          },2000)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },



  getMasse () {


    var _this = this
    wx.requestSubscribeMessage({
      tmplIds: ["2B8PLmOrI1YFdosio5jprIOfkwwXXBJdw2s5p-jzfvk"],
              success: (res) => {

                console.log(res)
                if (res['2B8PLmOrI1YFdosio5jprIOfkwwXXBJdw2s5p-jzfvk'] === 'accept') {


                  _this.getDingyue(1)

                } else {

                  _this.getDingyue(0)
                  // setTimeout(function () {
                  //   wx.navigateBack()
                  // }, 2000)
                }

              },
              fail(err) {
                //失败
                console.error(err);
                // reject()
              }
            })
  },

    //邮寄创建订单接口

    crateOrder (params,type) {
      var _this = this
      wx.request({
        url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/donate/preOrder/auth',
        data: params,
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token" : wx.getStorageSync('token'),
          "uid" : wx.getStorageSync('uuid')
        },
        success: (res) =>  {
          console.log(res)

          if (res.data.success) {

            _this.clearNextpage()
            wx.showToast({
              title: type != undefined && type != null && type != '' ? '更换成功' : '创建成功',
              icon: 'none',
              duration: 2000
            })

            _this.setData({
              type: 1,
              orderNo2: res.data.data.orderNo
            })

            _this.getStatusopen()



            // wx.requestSubscribeMessage({
            //   tmplIds: ["2B8PLmOrI1YFdosio5jprIOfkwwXXBJdw2s5p-jzfvk"],
            //   success: (res) => {

            //     console.log(res)
            //     if (res['2B8PLmOrI1YFdosio5jprIOfkwwXXBJdw2s5p-jzfvk'] === 'accept') {
            
            //     } else {
            //       // setTimeout(function () {
            //       //   wx.navigateBack()
            //       // }, 2000)
            //     }

            //   },
            //   fail(err) {
            //     //失败
            //     console.error(err);
            //     // reject()
            //   }
            // })


            // return


            

            // var pages = getCurrentPages(); // 当前页面
            // var beforePage = pages[pages.length - 2];
            // beforePage.clearList()


            // if (params.bookInfoIds.split(',').length < 6) {
            //   _this.wxPay(res.data.data)
            // }else{
              // setTimeout(function () {
              //   wx.navigateBack()
              // }, 2000)
            // }


            // _this.getOrderNo(res.data.data.orderNo,params.bookInfoIds,params.shippingAddressId,params.shipType)

      //       setTimeout(function(){
      //           wx.navigateTo({
      //   url: '/package/juanshu/pages/paySuccess/paySuccess',
      // })
      //       },1000)
          }else{
             wx.showToast({
               title: res.data.msg,
               icon: 'none'
             })
          }
        }
      })
    },


  clearNextpage () {
    var params = {}

    if (this.data.wasActivities == 1) {
      params.wasActivities = 1
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/book/updateWasUpAdmin/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {

      }
    })
  },


  getOrderNo(orderNo, bookInfoIds,shippingAddressId, shipType) {

    var _this = this
    var params = {
      orderNo:orderNo,
      bookInfoIds:bookInfoIds,
      shippingAddressId:shippingAddressId,
      shipType:shipType,
      openId: wx.getStorageSync('openid')
    }

    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/donate/preOrder/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.success) {
          // wx.showToast({
          //   title: '订单创建成功，请在卖书列表中查看',
          //   icon: 'none',
          //   duration: 2000
          // })

          //邮寄订单创建成功
          _this.setData({
            type: 1,
            orderNo2: orderNo
          })

          var pages = getCurrentPages(); // 当前页面
          var beforePage = pages[pages.length - 2];
          beforePage.clearList()

          if (params.bookInfoIds.split(',').length < 6) {
            _this.wxPay(res.data.data)
          }
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })

  },



  wxPay(data) {

    console.log(data.timeStamp)

    // wx.navigateToMiniProgram({
    //   appId: 'wxdd8c93c8a6b5df1c',
    //   path: 'pages/sdx/index',
    //   extraData: {
    //     "orderNo": data.orderNo,
    //     "payCount": 5
    //   },
    //   //envVersion: 'develop',
    //   fail(res) {
    //     wx.showToast({
    //       title: res.errMsg,
    //       icon: 'none',
    //     });
    //   },
    //   success(res) {
    //     wx.showToast({
    //       title: 'ok',
    //       icon: 'none',
    //     });
    //   },
    // });
    // console.log(data.timeStamp)
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.sign,
      success: function (event) {
        wx.showToast({
          title: '支付成功',
          icon: 'none',
          duration: 2000
        })
        setTimeout(function () {
          wx.navigateBack()
        }, 2000)
      },
      fail: function (error) {
        console.log(error)
        wx.showToast({
          title: '支付失败',
          icon: 'none',
          duration: 2000
        })
        setTimeout(function () {
          wx.navigateBack()
        }, 2000)
      },
      complete: function (e) {
        if (e.errMsg == 'requestPayment:ok') {
          wx.showToast({
            title: '支付成功',
            icon: 'none',
            duration: 2000
          })
          setTimeout(function () {
            wx.navigateBack()
          }, 2000)
        }
      }
    })
  },

  wxPay2(orderNo) {

    // console.log(data.timeStamp)

    wx.navigateToMiniProgram({
      appId: 'wxdd8c93c8a6b5df1c',
      path: 'pages/sdx/index',
      extraData: {
        "orderNo": orderNo,
        "payCount": 5
      },
      //envVersion: 'develop',
      fail(res) {
        wx.showToast({
          title: res.errMsg,
          icon: 'none',
        });
      },
      success(res) {
        wx.showToast({
          title: 'ok',
          icon: 'none',
        });
      },
    });

    return
    console.log(data.timeStamp)
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.sign,
      success: function (event) {
        wx.showToast({
          title: '支付成功',
          icon: 'none'
        })
      },
      fail: function (error) {
        console.log(error)
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        })
      },
      complete: function (e) {
        if (e.errMsg == 'requestPayment:ok') {
          wx.showToast({
            title: '支付成功',
            icon: 'none'
          })
        }
      }
    })
  },


    // 接口部分

  //地址列表
    getLocalList(params) {

      var _this = this
      wx.request({
        url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/address/list/auth',
        data: params,
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token" : wx.getStorageSync('token'),
          "uid" : wx.getStorageSync('uuid')
        },
        success: (res) => {
          console.log(res)

          if (res.data.code == 200) {

            if (res.data.data.resultList.length!=0) {
            for (var i = 0; i < res.data.data.resultList.length; i++) {
              if (i==0) {
                res.data.data.resultList[i].ischoose = true
                _this.setData({
                  shippingAddressId: res.data.data.resultList[i].id
                })
              }else{
                res.data.data.resultList[i].ischoose = false
              }
            }

            var list = res.data.data.resultList

            _this.setData({
              locationList: list
            })
            }else{
              _this.setData({
                locationList:[],
                shippingAddressId: ''
              })
            }
          }else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      })
    },

    //删除地址
    shanchu(e) {

      var _this = this
      console.log(e.currentTarget.dataset.localid)
      var localid = e.currentTarget.dataset.localid
      wx.showModal({
        title: '删除地址',
        content: '确定删除该地址',
        success: function (res) {
          if (res.cancel) {
            return false
          }else{
            _this.shanchuApi(localid)
          }
        }
      })
    },

    shanchuApi (id) {
      var _this = this
      var params = {
        ids: id
      }
      wx.request({
        url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/address/del/auth',
        data: params,
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token" : wx.getStorageSync('token'),
          "uid" : wx.getStorageSync('uuid')
        },
        success: (res) => {
          console.log(res)

          if (res.data.code==200) {
            wx.showToast({
              title: '删除成功',
              icon: 'none'
            })
            _this.getLocalList(_this.data.params)
          }else{
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      })
    },


    // 选择地址

    choooseLocal (e) {

      console.log(e.currentTarget.dataset.localids)

      var ids = e.currentTarget.dataset.localids

      for (var i = 0; i < this.data.locationList.length;i++) {
        var ischoose = "locationList[" + i + "].ischoose"
        if (ids == this.data.locationList[i].id) {
          this.setData({
            [ischoose]: true,
            shippingAddressId: ids
          })
        }else{
          this.setData({
            [ischoose]: false
          })
        }
      }
    },


    onLoad (options) {
      // console.log(options.bookInfoIds)

      this.setData({
        options: options
      })

      if (options.wasActivities==1) {
        this.setData({
          wasActivities: options.wasActivities
        })
      }

      this.setData({
        hasOrder: this.data.options.orderNo ? true: false
      })
      if (options.bookInfoIds) {
        this.setData({
          arr: options.bookInfoIds.split(',')
        })
      }
      if (options.type) {
        wx.setNavigationBarTitle({
          title: '管理地址'
        })
        this.setData({
          localType: 1
        })
      }else{
        wx.setNavigationBarTitle({
          title: '确认收件地址'
        })
        this.setData({
          localType: 2
        })
      }
      this.setData({
        bookInfoIds: options.bookInfoIds,
        shipType: options.shipType,
        bookLength: options.bookLength,
        allScore: options.allScore
      })
    },

    //头部配送方式
    tabClick(e) {
      console.log(e.currentTarget.dataset.type)
      const type = e.currentTarget.dataset.type
      this.setData({
        shipType: type
      })

      if (this.data.shipType == 2) {
        this.loactionInfo()
      }
    },
  //获取定位信息
  loactionInfo() {
    var _this = this
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res)
        if (res.errMsg == 'getLocation:ok') {
          _this.setData({
            showCon: false,
            latitude: res.latitude,
            longitude: res.longitude
          })

          wx.removeStorageSync('lat')
          wx.removeStorageSync('long')
          wx.setStorageSync('lat', res.latitude)
          wx.setStorageSync('long', res.longitude)

          _this.getLocationName(res.latitude, res.longitude)
        }
      },
      fail: function (error) {
        _this.setData({
          showCon: true
        })
      }
    })
  },

  getLocationName(latitude, longitude) {
    wx.showLoading({
      title: '定位中',
      mask: true
    })
    var _this = this
    wxMap.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(res)
        if (res.message == 'query ok') {
          wx.hideLoading()
          _this.setData({
            locationName: res.result.address_component.city
          })
          wx.removeStorageSync('locationName')
          wx.setStorageSync('locationName', res.result.address_component.city)
          _this.getHuishouList(latitude, longitude, res.result.address_component.city)
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '定位失败',
          icon: 'none'
        })
      }
    })
  },

  //取消设置弹框
  changeModalCancel() {
    this.setData({
      showCon: false,
      shipType: 1
    })
  },
  openSetting2(e) {
    console.log(e)
    if (e.detail.authSetting["scope.userLocation"]) {
      this.loactionInfo()
    } else {
      wx.showToast({
        title: '未设置',
        icon: 'none'
      })
    }
  },
  //获取书籍回收驿站列表

  getHuishouList(latitude, longitude, city) {
    var _this = this
    var params = {
      pageNum: 1,
      pageSize: 999999,
      city: city,
      latitude: latitude,
      longitude: longitude
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/sdxBookStation/list/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          _this.setData({
            localNum: res.data.data.resultList.length,
            localList: res.data.data.resultList,
            bookStationId: res.data.data.resultList[0].id
          })
          var params = {
            bookInfoIds: _this.data.bookInfoIds,
            shipType: _this.data.shipType,
            bookStationId: _this.data.bookStationId,
            openId: wx.getStorageSync('openid')
          }

          if (_this.data.wasActivities!='') {
            _this.setData({
              params3: {
                bookInfoIds: _this.data.bookInfoIds,
                shipType: _this.data.shipType,
                bookStationId: _this.data.bookStationId,
                openId: wx.getStorageSync('openid'),
                wasActivities: _this.data.wasActivities
              }
            })
          }else{
            _this.setData({
              params3: {
                bookInfoIds: _this.data.bookInfoIds,
                shipType: _this.data.shipType,
                bookStationId: _this.data.bookStationId,
                openId: wx.getStorageSync('openid')
              }
            })
          }
         
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  // 更换卖书方式
  changeType() {

    if (this.data.fromType == 1) {
      this.closePop(2)
    } else {
      this.closePop(1)
    }
  },


  getScancode() {

    var _this = this
    if (this.data.type == '') {
      this.crateOrder2(this.data.params3)

      return
    }

    if (this.data.type == 2) {
      wx.showToast({
        title: '不要重复下单',
        icon: 'none'
      })

      return
    }

    if (this.data.type == 1) {
       wx.showModal({
      title: '更换配送方式',
      content: '是否更换配送方式',
      success: function (res) {
        if (res.confirm) {
          _this.closePop2(_this.data.orderNo2, _this.data.params3)
        }else{
          return false
        }
      }
    })
  }

    // wx.navigateBack()
  },


  //打开地图导航
  openMap(e) {
    const latitude = e.currentTarget.dataset.lat

    const longitude = e.currentTarget.dataset.long

    // console.log(latitude)

    // console.log(longitude)

    // return
    const name = e.currentTarget.dataset.name

    const address = e.currentTarget.dataset.address
    var _this = this
    wx.getLocation({
      type: 'wgs84', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        // 30.214600, 120.178520
        wx.openLocation({
          latitude: Number(latitude),//要去的纬度-地址
          longitude: Number(longitude),//要去的经度-地址
          name: name,
          address: address
        })
      }
    })
  },


  closePop2 (orderNo,params2) {
    var _this = this
    var params = {
      orderNo: orderNo
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/donate/donate/cancel/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          if (params2.shipType == 1) {
            _this.crateOrder(params2,1)
          }
          if (params2.shipType == 2) {
            _this.crateOrder2(params2,2)
          }
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  //取消订单
  closePop(type) {

    var _this = this
    wx.showLoading({
      title: '订单取消中',
      mask: true
    })
    var params = {
      orderNo: this.data.fromType == 1 ? this.data.orderId : this.data.orderNo
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/donate/donate/cancel/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.hideLoading()
          wx.showToast({
            title: '订单取消成功',
            icon: 'none',
            duration: 2000
          })
          _this.setData({
            pop: false
          })
          setTimeout(function () {
            if (_this.data.fromType == 1) {
              wx.navigateBack()
            } else {

              var pages = getCurrentPages(); // 当前页面
              var beforePage = pages[pages.length - 2];

              beforePage.cutOrder(_this.data.orderNo)

              if (type == 1) {
                wx.redirectTo({
                  url: '/package/juanshu/pages/buyBook/buyBook?bookInfoIds=' + JSON.stringify(_this.data.bookInfoIds),
                })
              } else {
                wx.navigateBack()
              }
            }
          }, 2000)
        } else {

          wx.hideLoading()

          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })

        }
      }
    })
    // this.setData({
    //   pop: false
    // })
  },

  // 放弃本次卖书
  popOpen() {
    this.setData({
      pop: true
    })
  },


  //自送下单
  //自送创建订单接口

  crateOrder2(params,type) {
    var _this = this

    wx.showLoading({
      title: '订单创建中',
      mask: true
    })

    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/donate/preOrder/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        console.log(res)

        if (res.data.success) {

          _this.clearNextpage()

          wx.hideLoading()
          _this.setData({
            orderId: res.data.data,
            type: 2,
            orderNo2: res.data.data.orderNo,
            cancelInfo: res.data.data.cancelInfo
          })
          wx.showToast({
            title: type!= undefined && type != null && type != '' ? '更换成功' :'订单创建成功,请在卖书列表中查看',
            icon: 'none',
            duration: 2000
          })


          _this.getStatusopen()

          // setTimeout(function () {
          //   wx.navigateBack()
          // },2000)
          // var pages = getCurrentPages(); // 当前页面
          // var beforePage = pages[pages.length - 2];
          // beforePage.clearList()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
    onShow () {
      this.getLocalList(this.data.params)
    }
})
